﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Configuration.Assemblies;

namespace WHO_Auth_TNG_Win {
    public partial class OptionsDialog : Form {

        private bool firstStart;
        private MainWindow mainWindow;
        
        public OptionsDialog(MainWindow mainWindow, bool firstStart) {
            InitializeComponent();
            this.mainWindow = mainWindow;
            this.firstStart = firstStart;
            if (!firstStart) {
                labelWelcome.Text = "Options";
                buttonOk.Text = "Save and continue";
                buttonCancel.Text = "Cancel";

                //Read and apply user settings
                textUsername.Text = WHT_Auth.Properties.Settings.Default.username;
                textPassword.Text = mainWindow.auth.password;
                checkSavePassword.Checked = WHT_Auth.Properties.Settings.Default.savePassword;
                checkStartMinimized.Checked = WHT_Auth.Properties.Settings.Default.startMinmized;
                
                //Autostart
                string keyName = "WHO-Auth TNG";
                string assemblyLocation = Application.ExecutablePath;
                checkStartWithWindows.Checked = AutoStart.IsAutoStartEnabled(keyName, assemblyLocation);
                
            }
            comboBox1.SelectedIndex = WHT_Auth.Properties.Settings.Default.quitAction;
            if (WHT_Auth.Properties.Settings.Default.quitAction < 0 || WHT_Auth.Properties.Settings.Default.quitAction > 2) {
                comboBox1.SelectedIndex = 0;
            }
            textUsername.Focus();
        }

        private void buttonOk_Click(object sender, EventArgs e) {
            if (verifyInput() || (!verifyInput() && MessageBox.Show(this, "The user name you provided may not be correct. Do you want to to continue anyway?", "Username invalid", MessageBoxButtons.YesNo) == DialogResult.Yes)) {

                bool credentialsChanged = (WHT_Auth.Properties.Settings.Default.username != textUsername.Text || mainWindow.auth.password != textPassword.Text);

                WHT_Auth.Properties.Settings.Default.username = textUsername.Text;
                WHT_Auth.Properties.Settings.Default.savePassword = checkSavePassword.Checked;
                WHT_Auth.Properties.Settings.Default.startMinmized = checkStartMinimized.Checked;
                WHT_Auth.Properties.Settings.Default.quitAction = comboBox1.SelectedIndex;

                //Password
                if (checkSavePassword.Checked) {
                    WHT_Auth.Properties.Settings.Default.password = Base64.Encode(textPassword.Text);
                } else {
                    WHT_Auth.Properties.Settings.Default.password = "";
                }

                //Autostart
                string keyName = "WHO-Auth TNG";
                string assemblyLocation = Application.ExecutablePath;
                if (checkStartWithWindows.Checked) {
                    AutoStart.SetAutoStart(keyName, assemblyLocation);
                } else {
                    if (AutoStart.IsAutoStartEnabled(keyName, assemblyLocation))
                        AutoStart.UnSetAutoStart(keyName);
                }

                mainWindow.auth.password = textPassword.Text;
                WHT_Auth.Properties.Settings.Default.Save();
                if (firstStart) {
                    //Check connection and use credentials if needed
                    mainWindow.auth.initialize();
                } else {
                    if (credentialsChanged) {
                        //Ask if user wants to test the new entered credentials
                        if (mainWindow.auth.isConnected()) {
                            DialogResult testNow = MessageBox.Show(mainWindow, "You changed your credentials. Do you want to test them now?\n For this the program" +
                                "will attempt a logout followed by a login. You might lose standing internet connections by this.\n" +
                                "If you don't test them and you made a mistake the next time a login is needed the program won't be\n" +
                                "able to log you in.", "Test credentials?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                            if (testNow == DialogResult.Yes) {
                                mainWindow.auth.doLogout();
                                mainWindow.auth.doLogin();
                            }
                        } else {
                            //Not connected. If login failed or was rejected, try again
                            if (mainWindow.savedAuthCode == AuthCode.LOGIN_REJECTED
                                || mainWindow.savedAuthCode == AuthCode.LOGIN_FAILED) 
                            {
                                mainWindow.auth.doLogin();
                            }
                        }
                    }
                }
                this.Close();
            }

            

        }

        private void buttonCancel_Click(object sender, EventArgs e) {
            if (firstStart) {
                //Dirty but it works. Look for nicer solution
                Application.Exit();
            }
            this.Close();
        }

        private bool verifyInput() {
            Regex exp = new Regex(@"[a-z]{5}[0-9]{2}", RegexOptions.IgnoreCase);
            MatchCollection MatchList = exp.Matches(textUsername.Text);
            if (MatchList.Count < 1)
                return false;
            else
                return true;

        }

        private void OptionsDialog_Load(object sender, EventArgs e) {

        }
    }
}
